package com.moli.iov.down.command.codec.utils;

import com.moli.iov.util.ByteArrayUtil;
import org.apache.commons.lang.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <p>
 *
 * </p>
 *
 * @author: zql
 * @Date: 2018/11/30 11:32
 */
public class ProtocolAnalysisUtil {

    protected static final Logger logger = LoggerFactory.getLogger(ProtocolAnalysisUtil.class);

    /**
     * 协议最小长度
     */
    private static final int PROTOCOL_MIN_LEN = 22;

    private ProtocolAnalysisUtil(){}


    /**
     * 解析协议
     * @param data
     * @return
     */
    public static  Protocol decode(byte[] data){
        if(data == null || data.length < PROTOCOL_MIN_LEN){
            logger.error("解析协议 异常，data为null 或长度小于22");
            return null;
        }

        byte[] startTag = ArrayUtils.subarray(data, 0, 2);
        data = ArrayUtils.subarray(data, 2, data.length);

        byte[] commandTag = ArrayUtils.subarray(data, 0, 1);
        data = ArrayUtils.subarray(data, 1, data.length);

        byte[] responseTag = ArrayUtils.subarray(data, 0, 1);
        data = ArrayUtils.subarray(data, 1, data.length);

        byte[] vin = ArrayUtils.subarray(data, 0, 17);
        data = ArrayUtils.subarray(data, 17, data.length);

        byte[] encryptTag = ArrayUtils.subarray(data,0 , 1);
        data = ArrayUtils.subarray(data, 1, data.length);

        byte[] dataLen = ArrayUtils.subarray(data, 0,  2);
        data = ArrayUtils.subarray(data, 2, data.length);
        int dataLenInt = ByteArrayUtil.toInt(dataLen);
        byte[] dataP = null;
        if(dataLenInt > 0){
            dataP = ArrayUtils.subarray(data, 0,  dataLenInt);
            data = ArrayUtils.subarray(data, dataLenInt, data.length);
        }

        byte[] checkCode = ArrayUtils.subarray(data, 0, 1);

        Protocol protocol = new Protocol();
        protocol.setStartTag(startTag)
                .setCommandTag(commandTag[0])
                .setResponseTag(responseTag[0])
                .setVin(ByteArrayUtil.asciiToStr(vin))
                .setEncryptTag(encryptTag)
                .setDataLen(dataLenInt)
                .setCheckCode(checkCode[0]);
        if(dataLenInt > 0 ){
            protocol.setData(dataP);
        }
        return protocol;
    }
}
